const { contextBridge, ipcRenderer } = require('electron');
let isMessageListenerRegistered = false; // 新增的标志变量
contextBridge.exposeInMainWorld('electronAPI', {
  // sendNotification: (title, body) => {
  //   ipcRenderer.send('notify', { title, body });
  // },

  // openChatWindow: () => {
  //   ipcRenderer.send('open-chat-window');
  // },

  ipcRenderer: {
    send: (channel, ...args) => ipcRenderer.send(channel, ...args),
    on: (channel, callback) => ipcRenderer.on(channel, callback),
  },

  socket: {
    connect: (host, port,user) => ipcRenderer.invoke('socket-connect', host, port,user),
    send: (data) => ipcRenderer.send('socket-send', data),
    onMessage: (callback) =>{
      if (!isMessageListenerRegistered) {
        ipcRenderer.on('socket-message', (_event, msg) => {
          console.log('Received message type:', typeof msg); // 应输出 'object'
          console.log('Received message content:', msg);
          callback(msg);
        });
        isMessageListenerRegistered = true;
      }
    }
  },
  saveToken: (token) => ipcRenderer.send('save-token', token),
  getToken: () => ipcRenderer.invoke('get-token'),
  getUsername:()=>ipcRenderer.invoke('get-username'),
  // 可扩展更多接口，如文件操作、系统 API 调用
});
